﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.InventoryCommands
{

    public class InventorySearchHandler : IRequestHandler<InventorySearchCommand, Result>
    {
        private readonly IBaseRepository<SleepInfor> SleepInforbaseRepository;
        private readonly IBaseRepository<Variety> VarietybaseRepository;

        public InventorySearchHandler(IBaseRepository<SleepInfor> sleepInforbaseRepository, IBaseRepository<Variety> varietybaseRepository)
        {
            SleepInforbaseRepository = sleepInforbaseRepository;
            VarietybaseRepository = varietybaseRepository;
        }

        public async Task<Result> Handle(InventorySearchCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.search };
            var list = (from a in SleepInforbaseRepository.GetAll()
                        join b in VarietybaseRepository.GetAll() on a.VarietyId equals b.VarietyId
                        select new GroupDto()
                        {
                            Gender = a.Gender,
                            VarietyId = a.VarietyId,
                            VarietyName = b.VarietyName,
                        }).ToList();
            if (request.Gender > 0)
            {
                list = list.Where(x => x.Gender == request.Gender).ToList();
            }
            list = (from a in SleepInforbaseRepository.GetAll()
                    join b in VarietybaseRepository.GetAll() on a.VarietyId equals b.VarietyId
                    where a.Gender == request.Gender
                    group a by b.VarietyName into b
                    select new GroupDto
                    {
                        VarietyName = b.Key,
                        Count = b.Count()
                    }).ToList();

            result.Data = list;
            return result;
        }
    }
}
